<template>
	<view class="container">
		<!-- 自定义顶部导航栏 -->
		<view class="custom-app-bar-wrapper" :style="{ height: `calc(100rpx + ${statusBarHeight}px)` }">
			<view class="custom-app-bar" :style="{ top: statusBarHeight + 'px' }">
				<u-icon name="arrow-left" size="40" class="back-icon" @click="goBack"></u-icon>
				<text class="title">选择书籍</text>
			</view>
		</view>

		<!-- 内容区域 -->
		<view class="content" :style="{ paddingTop: `calc(100rpx + ${statusBarHeight}px)` }">
			<!-- 绘本集列表 -->
			<view class="bookshelf-section" v-if="!selectedBookShelf">
				<view class="section-title">选择绘本集</view>
				<view class="bookshelf-list">
					<view class="bookshelf-item" v-for="bookshelf in bookShelfList" :key="bookshelf.id" @click="selectBookShelf(bookshelf)">
						<view class="bookshelf-info">
							<view class="bookshelf-title">{{ bookshelf.title }}</view>
							<view class="bookshelf-meta">
								<text class="bookshelf-count">{{ bookshelf.bookCount }}本</text>
								<text class="bookshelf-type">{{ bookshelf.type }}</text>
							</view>
						</view>
						<u-icon name="arrow-right" size="16" color="#999"></u-icon>
					</view>
				</view>
			</view>

			<!-- 书籍列表 -->
			<view class="books-section" v-if="selectedBookShelf">
				<view class="section-header">
					<u-icon name="arrow-left" size="24" color="#007aff" @click="backToBookShelfList"></u-icon>
					<text class="section-title">{{ selectedBookShelf.title }}</text>
				</view>
				<view class="books-grid">
					<view class="book-item" v-for="book in bookList" :key="book.id" @click="toggleBookSelection(book)">
						<view class="book-cover-container">
							<image class="book-cover" :src="getBookCoverUrl(book)" mode="aspectFit"></image>
							<view class="book-checkbox" :class="{ selected: isBookSelected(book.id) }">
								<u-icon name="checkmark" size="16" color="#fff" v-if="isBookSelected(book.id)"></u-icon>
							</view>
						</view>
						<text class="book-name">{{ book.bookName }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部确认栏 -->
		<view class="footer-bar" v-if="selectedBookShelf">
			<view class="selected-info">
				<text>已选择 {{ selectedBooks.length }} 本书籍</text>
			</view>
			<u-button type="primary" size="medium" shape="circle" @click="confirm" :disabled="selectedBooks.length === 0">
				确认选择
			</u-button>
		</view>
	</view>
</template>

<script>
	import * as BookShelfApi from '@/api/bookShelf'
	import * as BookApi from '@/api/book'

	export default {
		data() {
			return {
        type: '',
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				bookShelfList: [], // 绘本集列表
				selectedBookShelf: null, // 当前选中的绘本集
				bookList: [], // 当前绘本集的书籍列表
				selectedBooks: [], // 已选择的书籍
				loading: false
			};
		},
		onLoad(options) {
      this.type = options.type || ''; // 获取type参数，如果没有则默认为空
      console.log('接收到的type参数:', this.type);
			this.getBookShelfList(this.type);
		},
		methods: {
				// 获取书籍封面URL
			getBookCoverUrl(book) {
				if (book.coverUrl) {
					return book.coverUrl;
				}
				if (book.url && book.url.trim()) {
					// 处理逗号分隔的图片名称，取第一张
					const imageNames = book.url.split(',');
					if (imageNames.length > 0 && imageNames[0].trim()) {
						return `/static/url/${imageNames[0].trim()}`;
					}
				}
				// url为空时默认显示defualt_1.png
				return '/static/url/defualt_1.png';
			},

      // 获取绘本集列表
      async getBookShelfList(type) {
        this.loading = true;
        try {
          // 获取英文和中文书架的绘本集
          const [englishResponse, chineseResponse] = await Promise.all([
            BookShelfApi.getCategoryList({type: '1'}),
            BookShelfApi.getCategoryList({type: '2'})
          ]);

          if(type==='1'){
            console.log("1111111")
            this.bookShelfList = englishResponse.data;
          }else{
            console.log("2222222")
            this.bookShelfList = chineseResponse.data;
          }
          console.log("bookShelfList" + this.bookShelfList);
        } catch (error) {
          console.error('获取绘本集列表失败:', error);
          uni.showToast({
            title: '获取绘本集列表失败',
            icon: 'none'
          });
        } finally {
          this.loading = false;
        }
      },

			// 选择绘本集
			async selectBookShelf(bookShelf) {
				this.selectedBookShelf = bookShelf;
				await this.loadBookList(bookShelf.id);
			},

			// 获取书籍列表
			async loadBookList(bookShelfId) {
				this.loading = true;
				try {
					const response = await BookApi.getBookList({
						pageNo: '1',
						pageSize: '100',
						bookShelfId: bookShelfId.toString()
					});

					if (response.code === 0 && response.data) {
						this.bookList = response.data.list || [];
					} else {
						uni.showToast({
						title: response.msg || '获取书籍列表失败',
						icon: 'none'
					});
					}
				} catch (error) {
					console.error('获取书籍列表失败:', error);
				uni.showToast({
					title: '获取书籍列表失败',
					icon: 'none'
				});
				} finally {
					this.loading = false;
				}
			},

			// 返回绘本集列表
			backToBookShelfList() {
				this.selectedBookShelf = null;
				this.bookList = [];
				this.selectedBooks = [];
			},

			// 切换书籍选择状态
			toggleBookSelection(book) {
				const index = this.selectedBooks.findIndex(item => item.id === book.id);
				if (index > -1) {
					// 已选择，取消选择
					this.selectedBooks.splice(index, 1);
				} else {
					// 未选择，添加选择
				this.selectedBooks.push({
					id: book.id,
					bookName: book.bookName,
					coverUrl: this.getBookCoverUrl(book),
					url: book.url // 保留原始url字段供后续使用
				});
				}
			},

			// 判断书籍是否已选择
			isBookSelected(bookId) {
				return this.selectedBooks.some(item => item.id === bookId);
			},

			// 确认选择
			confirm() {
				if (this.selectedBooks.length === 0) {
				uni.showToast({
					title: '请至少选择一本书籍',
					icon: 'none'
				});
				return;
			}

				// 生成bookIds字符串
				const bookIds = this.selectedBooks.map(book => book.id).join('_');

				// 通过事件通道返回选择结果
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('selectBooks', {
					bookIds: bookIds,
					selectedBooks: this.selectedBooks
				});

				// 返回上一页
				uni.navigateBack();
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			}
		}
	};
</script>

<style lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f7f7f7;
	}

	.custom-app-bar-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff;
	}

	.custom-app-bar {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		padding: 0 20rpx;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	}

	.back-icon {
		position: absolute;
		left: 20rpx;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.content {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.section-header {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 20rpx;
	}

	.bookshelf-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.bookshelf-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.bookshelf-info {
		flex: 1;
	}

	.bookshelf-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 8rpx;
	}

	.bookshelf-meta {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.bookshelf-count {
		font-size: 24rpx;
		color: #666;
	}

	.bookshelf-type {
		font-size: 22rpx;
		color: #007aff;
		background-color: rgba(0, 122, 255, 0.1);
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
	}

	.books-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
	}

	.book-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 16rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.book-cover-container {
		position: relative;
		margin-bottom: 12rpx;
	}

	.book-cover {
		width: 120rpx;
		height: 150rpx;
		border-radius: 8rpx;
		background-color: #e5e5e5;
	}

	.book-checkbox {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		border: 2rpx solid #ddd;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;

		&.selected {
			background-color: #007aff;
			border-color: #007aff;
		}
	}

	.book-name {
		font-size: 24rpx;
		color: #333;
		text-align: center;
		max-width: 120rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.footer-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1rpx solid #e5e5e5;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	.selected-info {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}
</style>
